import { style } from '@angular/animations'
import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'
import { Router, ActivatedRoute } from '@angular/router'

declare var $: any
declare var BMap: any
declare var BMapLib: any
declare var toMapPoint: any
@Component({
  selector: 'sa-stuff-worktime',
  templateUrl: './stuff-worktime.component.html'
})
export class StuffWorktimeComponent implements OnInit {
  tableData: any = [] //table数据

  totalCount: number = 0 //分页总条数
  curPage: number = 0 //分页当前页
  pageSize: number = 10 //分页每页条数
  searchKey: string = '' //搜索keyword
  btnData: any = []
  dataExport: boolean = false
  startTime: string = ''
  endTime: string = ''
  isShowRoot: boolean = false
  userTypeList: any = [] // 用户类型列表
  repairPointList: any[] = []

  searchParams = {
    userType: '',
    companyId: '',
    outsourcingTeamId: '',
    outsourcingTeamName: '',
    workerType: '',
    rapirPoints: '',
    relationType: '1',
    dutyType: '1'
  }

  specifyTime: any = {
    startTime: '',
    endTime: ''
  }
  teamApi: string = 'user/teamTree.html' // 实施团队 api
  rapirPointsApi: string = 'maintenance/getRepairPointInfo.html' //  维修点查询接口

  timeRecordsData: any[] = []

  map: any //百度地图
  markerClusterer: any //聚能合marker对象
  overlayArr: any[] = [] //根据piont调整视野

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }

  //初始化钩子函数
  ngOnInit() {
    let nowTime = new Date()
    let _startTime = common.getTimeMmss(nowTime)
    const baseDate = _startTime.slice(0, 10)
    this.startTime = baseDate + ' 00:00:00'
    this.endTime = baseDate + ' 23:59:59'
    this.specifyTime = {
      startTime: this.startTime,
      endTime: this.endTime
    }
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        this.initAllRepairPoint().then(() => {
          this.initRepairPointSelect2()
        })
      })
    })
    this.initBtn()
    this.initUserTypeList()
    this.load()
  }
  // 获取用户类型列表
  initUserTypeList() {
    this.jsonApiService.http('role/userTypeList.html', {}).subscribe(data => {
      if (data.success) {
        for (let index = 0; index < data.data.length; index++) {
          const element = data.data[index]
          element.text = element.userTypeName
          element.id = element.userType
        }
        this.userTypeList = data.data
      }
    })
  }
  // 站点数据
  initAllRepairPoint() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('maintenance/getRepairPointInfo.html', null).subscribe(data => {
        if (data.success) {
          var repairPointList = data.data
          var selectdata = []
          for (var i = 0; i < repairPointList.length; i++) {
            var obj = {
              id: repairPointList[i].id,
              text: repairPointList[i].repairPointName
            }
            selectdata[i] = obj
          }
        }
        that.repairPointList = selectdata
        resolve()
      })
    })
  }
  selectRow: any = {}
  recordTotalCount: number = 0 //分页总条数
  recordCurPage: number = 1 //分页当前页
  recordPageSize: number = 10 //分页每页条数

  //查看车辆列表
  viewRow(row, modal) {
    this.selectRow = row
    this.recordCurPage = 1
    this.recordPageSize = 10
    this.requestRecordList()
    modal.show()
  }

  closeViewModal(modal) {
    if(modal === 'mapModal'){
      this.map = null
    }
    modal.hide()
  }

  //请求车辆列表
  requestRecordList() {
    const baseDate = this.selectRow.statisticsDate.slice(0, 10)
    const start = baseDate + ' 00:00:00'
    const end = baseDate + ' 23:59:59'

    let data = {
      pageSize: this.recordPageSize,
      nowPage: this.recordCurPage,
      parameters: {
        startTime: start,
        endTime: end,
        userId: this.selectRow.userId
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('attendanceManage/pointList.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.timeRecordsData = data.exhibitDatas
        this.recordTotalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  recordPaginate(e) {
    this.recordCurPage = e.page + 1
    this.recordPageSize = e.rows
    this.requestRecordList()
  }

  recordRefresh() {
    this.recordCurPage = 1
    this.requestRecordList()
  }

  //刷新
  refresh() {
    this.curPage = 1
    this.load()
  }
  // 时间组件传递过来的数据
  getSelectTableTime(time) {
    this.startTime = time.startTime
    this.endTime = time.endTime
    // this.load()
  }
  //get权限按钮数据
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_outsource-management:stuff-worktime')))
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'stuff-worktime:exportBtn' && item.parentId) {
        this.dataExport = true
      }
    }
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  // 导出操作
  export() {
    const params = {
      name: this.searchKey,
      startTime: this.startTime,
      endTime: this.endTime,
      ...this.searchParams
    }
    common.exprotDataFile(params, 'param', config.BaseURL + 'attendanceManage/exportAttendenceListFile.html')
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        name: this.searchKey,
        startTime: this.startTime,
        endTime: this.endTime,
        ...this.searchParams
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('attendanceManage/list.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        data.exhibitDatas.forEach(el => {
          el.repairPointsStr = ''
          if (el.rapirPoints && el.rapirPoints.length > 0) {
            const temp = el.rapirPoints.map(el => el.repairPointName)
            el.repairPointsStr = temp.join(',')
          }
        })
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      }
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }

  companySelected(data) {
    this.searchParams.companyId = data.companyId || ''
    this.table_search()
  }

  companyList: any = []
  companyTeamSelected(data) {
    $('button[type="submit"]').removeAttr('disabled')
    this.searchParams.outsourcingTeamId = data.companyId || ''
    this.searchParams.outsourcingTeamName = data.companyName || ''
    this.companyList = data.companyList || []
    this.table_search()
  }

  // 站点配置
  initRepairPointSelect2() {
    let that = this
    // 站点-查询条件
    $('#repairPointSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.repairPointList
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.searchParams.rapirPoints = data.id
      })
  }

  // 删除站点-查询
  delRepairPoint() {
    this.searchParams.rapirPoints = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#repairPointSelect2').val('')
    $('#select2-repairPointSelect2-container').empty()
    $('#select2-repairPointSelect2-container').attr('title', '')
    $('#select2-repairPointSelect2-container').prepend(str)
  }

  /*          地图采点         */
  // 查看采点地图
  async viewMapModal(modal) {
    this.overlayArr = []
    modal.show()
    await this.initMap()
    this.requestMapData()
  }

  // 地图初始化
  initMap() {
    return new Promise((resolve, reject) => {
      try {
        const map = new BMap.Map('baiduMap', { enableMapClick: false }) //创建地图实例
        map.centerAndZoom(new BMap.Point(83.404, 53.915), 5)
        map.enableScrollWheelZoom(true) //地图的鼠标滚轮缩放
        map.addControl(new BMap.NavigationControl({ anchor: 3, offset: new BMap.Size(12, 68) }))
        map.addControl(new BMap.ScaleControl())
        // map.addControl(new BMap.MapTypeControl({ type: 2, anchor: 3, offset: new BMap.Size(85, 40) }))
        this.map = map

        this.markerClusterer = new BMapLib.MarkerClusterer(map)

        resolve(true)
      } catch (error) {
        reject()
      }
    })
  }

  //请求采点地图数据
  requestMapData() {
    const { statisticsDate, userId, rapirPoints } = this.selectRow
    const baseDate = statisticsDate.slice(0, 10)
    const start = baseDate + ' 00:00:00'
    const end = baseDate + ' 23:59:59'
    let companyIdsArr: any[] = []
    rapirPoints.forEach((el: any) => {
      if (el.companyArrays && el.companyArrays.length > 0) {
        const temp = el.companyArrays.map((company: any) => company.companyId)
        companyIdsArr = companyIdsArr.concat(temp)
      }
    })

    let data = {
      parameters: {
        startTime: start,
        endTime: end,
        userId,
        companyIds: companyIdsArr.join(',')
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('attendanceManage/allPointList.html', reqdata).subscribe(res => {
      if (res.success) {
        const { companyList, list } = res.data
        this.handleRailData(companyList)
        this.handlePiontData(list)
        setTimeout(() => {
          this.map.setViewport(this.overlayArr)
        }, 200)
      } else {
        this.jsonApiService.message(res.message)
      }
    })
  }

  // 处理并画采点数据
  handlePiontData(piontData: any[]) {
    const that = this
    const markers = []
    const points = []
    for (const item of piontData) {
      if (item.lng && item.lat) {
        const point = this.toBDMapPointObj(item.lng, item.lat)
        const marker = new BMap.Marker(point)
        marker.addEventListener('click', function (e: any) {
          that.showInfoWindow(item, point)
        })
        points.push(point)
        markers.push(marker)
      }
    }
    if (markers.length > 0) {
      that.markerClusterer.addMarkers(markers)
    }
    if (that.overlayArr.length === 0) {
      that.overlayArr = points
    }
  }

  showInfoWindow(data: Record<string, any>, point: any) {
    const content = `<div style="margin-bottom:10px;margin-top:30px;">状态：${
      data.status === '0'
        ? '<span style="color: #69aa46;">围栏内</span>'
        : '<span style="color: #d15b47;">围栏外</span>'
    } </div>采点时间：${data.collectTime}`

    const infoWindow = new BMap.InfoWindow(content, {
      width: 0,
      height: 80,
      title: '',
      offset: new BMap.Size(0, -12)
    })
    this.map.openInfoWindow(infoWindow, point)

    setTimeout(function () {
      if ($('.pointer').length < 1) {
        $('.BMap_bottom').append('<div class="pointer"></div>')
      }
    }, 50)
  }

  // 处理围栏数据
  handleRailData(railData: any[]) {
    railData.forEach((item: any) => {
      if (item.lng && item.lat) {
        const point = this.toBDMapPointObj(item.lng, item.lat)
        const circleOverlay: any = this.drawRail(point, item.radius)
        this.overlayArr = this.overlayArr.concat(circleOverlay.ha)
      }
    })
  }

  // 大地转百度坐标点(返回Point对象)
  toBDMapPointObj(lng: string | number, lat: string | number) {
    const pointToMap = toMapPoint({ lng, lat }) //大地转百度坐标系
    return new BMap.Point(pointToMap.lng, pointToMap.lat)
  }

  // 画围栏圆
  drawRail(point: any, radius: number) {
    const railStyle = {
      strokeColor: 'blue',
      fillColor: 'red',
      strokeWeight: 1,
      strokeOpacity: 0.2,
      fillOpacity: 0.2
    } //围栏圆样式

    const circle = new BMap.Circle(point, radius, railStyle) //创建圆
    this.map.addOverlay(circle)
    return circle
  }
}
